package com.twu.biblioteca.System;

import com.twu.biblioteca.Models.*;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by ubuntu on 4/28/14.
 */
public class Library {


    private Data data;
    public Library(Data data) {
        this.data = data;
        addNewItemList(Movie.class);
        addNewItemList(Book.class);
    }

    public <T extends Item> void addNewItemList(Class<T> classType){
        data.addNewListToLibraryItemLists(classType);
    }

    public <T extends Item> Item searchItemByName(String itemName, Class<? extends Item> classType) {
        ArrayList<? extends Item> allItems = getAllItems(classType);
        Iterator<? extends Item> itemIterator = null;
        if(allItems!=null)
            itemIterator = allItems.iterator();
        while (itemIterator.hasNext()) {
            Item currentItem = itemIterator.next();
            if(currentItem.getTitle().equalsIgnoreCase(itemName)) {
                return currentItem;
            }
        }
        return null;
    }

    public boolean available(String itemName,Class<? extends Item> classType) {
        Item searchedItem = searchItemByName(itemName,classType);
        return (searchedItem!=null && searchedItem.isAvailable());
    }

    public <T extends Item> void addItem(T itemToAdd, Class<T> classType) {
        ArrayList<T> allItems = getAllItems(classType);
        allItems.add(itemToAdd);
    }

    public <T extends Item> ArrayList<T> getAllItems(Class<T> classType) {
        return data.getLibraryItemLists(classType);
    }


    public <T extends Item> boolean borrowItem(String itemName, Class<T> classType) {
        Item itemToBorrow = searchItemByName(itemName, classType);
        if(itemToBorrow!=null) {
            return itemToBorrow.borrow(data.getLoggedInUser());
        }
        return false;
    }

    public<T extends Item> boolean returnBackToLibrary(String bookName,Class<T> classType) {
        Item itemToReturn = searchItemByName(bookName,classType);
        if(itemToReturn!=null && !itemToReturn.isAvailable())
            return itemToReturn.returnItem();
        return false;
    }



    public <T extends Item> String getBorrowerId(String itemName, Class<T> classType) {
        Item borrowedItem = searchItemByName(itemName, classType);
        if(!borrowedItem.isAvailable()) {
            return borrowedItem.getBorrowerId();
        }
        return null;
    }
}
